package com.bluesky.framework.config.mybatisplus.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.bluesky.common.exception.CustomException;
import com.bluesky.common.result.ResultCode;
import com.bluesky.common.util.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 * MP注入处理器
 *
 * @author Kevin
 */
public class CreateAndUpdateMetaObjectHandler implements MetaObjectHandler {

    public static final String CREATE_TIME = "createTime";
    public static final String UPDATE_TIME = "updateTime";

    public static final String CREATE_BY = "createBy";
    public static final String UPDATE_BY = "updateBy";

    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            if (metaObject.hasGetter(CREATE_TIME) && metaObject.getValue(CREATE_TIME) == null) {
                this.strictInsertFill(metaObject, CREATE_TIME, Date.class, new Date());
            }
            if (metaObject.hasGetter(CREATE_BY) && metaObject.getValue(CREATE_BY) == null) {
                this.strictInsertFill(metaObject, CREATE_BY, String.class, SecurityUtils.getLoginUser().getSysUser().getId().toString());
            }
            if (metaObject.hasGetter(UPDATE_TIME) && metaObject.getValue(UPDATE_TIME) == null) {
                this.strictUpdateFill(metaObject, UPDATE_TIME, Date.class, new Date());
            }
            if (metaObject.hasGetter(UPDATE_BY) && metaObject.getValue(UPDATE_BY) == null) {
                this.strictUpdateFill(metaObject, UPDATE_BY, String.class, SecurityUtils.getLoginUser().getSysUser().getId().toString());
            }
        } catch (Exception e) {
            throw new CustomException(ResultCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            if (metaObject.hasGetter(UPDATE_TIME) && metaObject.getValue(UPDATE_TIME) == null) {
                this.strictUpdateFill(metaObject, UPDATE_TIME, Date.class, new Date());
            }
            if (metaObject.hasGetter(UPDATE_BY) && metaObject.getValue(UPDATE_BY) == null) {
                this.strictUpdateFill(metaObject, UPDATE_BY, String.class, SecurityUtils.getLoginUser().getSysUser().getId().toString());
            }
        } catch (Exception e) {
            throw new CustomException(ResultCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

}
